package com.albon.main;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.albon.alarm.SoccerSetAlarm;
import com.albon.baseball.Baseball;
import com.albon.soccer.DatabaseHelper;
import com.albon.soccer.Soccer;
import com.albon.soccer.SoccerAdapter;
import com.albon.soccer.SoccerLeague;
import com.albon.soccer.SoccerParser;
import com.albon.sportsalarm.R;
import com.albon.util.JsonNetwork;
import com.albon.util.Logg;
import com.albon.util.NetworkComplete;
import com.albon.util.Schedule_Calendar;
import com.albon.util.UrlList;
@SuppressLint("ValidFragment")
public class SoccerFragment extends Fragment implements OnClickListener {
	private final String TAG = "SoccerFragment";
	
	
	
	private Schedule_Calendar sc;
    private ImageView btn_menu;
    private ImageView btn_month;
	private ListView listView;
	private TextView titleText;
	private TextView monthText;
	
    private TextView dayText;
	private Button dayPrevious;
    private Button dayNext;
    private Context mContext;
    
    static int TODAY = UrlList.TODAY;    
    private SoccerAdapter mSoccerAdapter;
   
    
    private String mYear; //올해
    private String mMonth; //이번달 
    private String mDay; //오늘
    
   
    
    private String league_title = "";
    private String league_name = "";
    private int world = 0;
    
    private DatabaseHelper mDBHelper = null;
    private SQLiteDatabase db = null;
    
	
	public SoccerFragment(String league_title, String league_name, int world) {
		//mColorRes = colorRes;
		this.league_title = league_title;
		this.league_name = league_name;
		this.world = world;
		setRetainInstance(true);
	}

	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mContext = getActivity();
		
		 mDBHelper = new DatabaseHelper(getActivity(), DatabaseHelper.DATABASE_NAME);
	        if(db == null){        	
	        	db = mDBHelper.getWritableDatabase(); 
			}
		return inflater.inflate(R.layout.soccer_league_day, container ,false);
		
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	
		init();	
		sc = new Schedule_Calendar();
		setDayText();
	}
	
	private void setDayText() {
		 mYear = sc.getCurYear();
	        mMonth = sc.getCurMonth();
	        mDay = sc.getCurDay();
			
			monthText.setText(mMonth);
			dayText.setText(mDay);	
			soccer_packet();	
    }
	
	boolean isProgress = true;
	ArrayList<Soccer> soccer = new ArrayList<Soccer>();
	public void soccer_packet(){
		Logg.e(TAG, "soccer_packet");
		ArrayList<String>nameList = new ArrayList<String>();
		ArrayList<String>postList = new ArrayList<String>();
		String urlString, dataType;
		nameList.clear();
		postList.clear();
		urlString = UrlList.IP+UrlList.SOCCER+UrlList.DAY+"/"+TODAY+"/"+league_name;
		dataType = UrlList.GET;
		JsonNetwork mNet = new JsonNetwork(getActivity(), nameList, postList, urlString, dataType);
		mNet.setNetWorkComplete(new NetworkComplete() {
			
			@Override
			public void onNetWorkComplete(boolean isSuccess, String jsonData) {
				// TODO Auto-generated method stub
				if(isSuccess)
				{
					try {
						JSONArray array = new JSONArray(jsonData);
						int size = array.length();
						soccer.clear();
						for(int i=0;i<size;i++)
						{
							JSONObject order = (JSONObject)array.get(i);
							Soccer mData = new Soccer(mContext, order.toString(), mYear, mMonth, mDay);
							//adapter에서 사용할 데이터 setBtnClicked,setmYear,setmMonth
							mData.setBtnClicked(Boolean.valueOf(mData.getEnable()));
							mData.setmYear(mYear);
							mData.setmMonth(mMonth);
							soccer.add(mData);
						}
						Logg.d(TAG, "soccer : "+soccer.size());
						listViewUpdate();
					} catch (Exception e) {
						// TODO: handle exception
						Logg.e(TAG, "e : "+e);
					}
				}else{
					
					if(jsonData!=null)
					{
						
					}
					else
					{
						Toast.makeText(getActivity(), UrlList.Error, 1000).show();
					}
				}
			}
		});
		mNet.setProgress(isProgress);
		mNet.onConnect();
	}
	private void init(){
		titleText = (TextView)getView().findViewById(R.id.title);
    	titleText.setText(league_title);
    	monthText = (TextView)getView().findViewById(R.id.monthText);
    	dayText = (TextView)getView().findViewById(R.id.dayText);
    	dayPrevious = (Button)getView().findViewById(R.id.dayPrevious);
    	dayPrevious.setOnClickListener(this);
    	dayNext = (Button)getView().findViewById(R.id.dayNext);
    	dayNext.setOnClickListener(this);  
    	
    	//data = new ArrayList<HashMap<String, String>>();
			
		listView = (ListView)getView().findViewById(R.id.listView1);
		
		btn_menu = (ImageView)getView().findViewById(R.id.btn_menu);
		btn_menu.setOnClickListener(this);    	
		btn_month = (ImageView)getView().findViewById(R.id.btn_month);
		btn_month.setOnClickListener(this);   	
    }
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
	}

	
	private void listViewUpdate() {
		
		mSoccerAdapter = new SoccerAdapter(getActivity(), R.layout.sports_row_item, soccer);
		mSoccerAdapter.notifyDataSetChanged();
		listView.setAdapter(mSoccerAdapter);
		//listView.setOnTouchListener(mOnTouchListener);
		listView.setOnItemClickListener(alarmOnItemClickListener);
	}
	
	//클릭이벤트
			AdapterView.OnItemClickListener alarmOnItemClickListener = new AdapterView.OnItemClickListener(){

				public void onItemClick(AdapterView parent, View view, int position,
						long id) {
					// TODO Auto-generated method stub
					Soccer soccer = (Soccer) view.getTag();
					//Log.d(TAG, "onClick id : "+id+", view id = "+soccer.getId());
					//Log.d(TAG, "onClick id : "+id+", soccer.getScore() = "+soccer.getScore());
					if(soccer.getScore().equals("")){ // 스코어가 없는것만 알람 설정할수 있도록
						Intent set_alarm_intent = new Intent(getActivity(), SoccerSetAlarm.class);
						set_alarm_intent.putExtra("league_title", league_title);
						set_alarm_intent.putExtra("compare_date", soccer.getCompare_date());
						set_alarm_intent.putExtra("a_team", soccer.getA_team());
						set_alarm_intent.putExtra("b_team", soccer.getB_team());
						set_alarm_intent.putExtra("real_date", soccer.getReal_date());
						set_alarm_intent.putExtra("real_time", soccer.getReal_time());
						set_alarm_intent.putExtra("year", mYear);
						set_alarm_intent.putExtra("month", mMonth);
						set_alarm_intent.putExtra("stadium", soccer.getStadium());
						
						startActivity(set_alarm_intent);
					}else{
						Toast.makeText(getActivity(), R.string.past_game, Toast.LENGTH_SHORT).show();
					}
				}
				
			};
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_back_menu:
			AlbonMain fca = (AlbonMain) getActivity();
			fca.getSlidingMenu().showMenu();
			
			break;
			
		case R.id.btn_month:
			break;
		case R.id.dayPrevious:			
			sc.setPreviousDay();
			--TODAY ;
			setDayText();
			break;
			
		case R.id.dayNext:
			
			sc.setNextDay();
			++TODAY ;
			setDayText();
			break;
		}
		
	}
	

}
